'''
Created on: 2/12/15

@author: Rich Plevin (rich@plevin.com)

Functions and data common to GCAM utilities (e.g., batchQuery, queueGCAM, csvDiff)
'''

# Copyright (c) 2015, Richard Plevin.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the
#    distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os
import io
import platform
from ConfigParser import SafeConfigParser

DEFAULT_SECTION = 'DEFAULT'
GCAM_SECTION    = 'GCAM'
USR_CONFIG_FILE = '.gcam.cfg'
CONFIG_VAR_NAME = 'QUEUE_GCAM_CONFIG_FILE'
WORKSPACE_VAR_NAME = 'QUEUE_GCAM_WORKSPACE'

#
# These are defaults for the batchQuery and queueGCAM utilities
#
_SystemDefaults = \
"""
[GCAM]
GCAM.Root               = %(Home)s/GCAM
GCAM.Current            = %(GCAM.Root)s/current
GCAM.Workspace          = %(GCAM.Current)s/Main_User_Workspace
GCAM.ModelInterface     = %(GCAM.Current)s/ModelInterface
GCAM.JavaLibPath        = %(GCAM.Workspace)s/libs/dbxml/lib
GCAM.JavaArgs           = -Xms512m -Xmx2g
GCAM.OutputDir          = %(GCAM.Workspace)s/output
GCAM.BatchFile          = generated_batch_file.xml
GCAM.QueryDir           =
GCAM.DefaultQueue       = standard
GCAM.QsubResources      = pvmem=6GB
GCAM.QsubEnviroVars     =
GCAM.ScenariosDir       = %(GCAM.Root)s/scenarios
GCAM.Minutes            = 20
GCAM.UseVirtualBuffer   = yes
GCAM.OutFilePatterns    = %(GCAM.Root)s/outFilePatterns.txt
GCAM.PostProcessor      =
"""

# Stub ~/.gcam.cfg file which user can edit
_UserDefaults = \
"""
[GCAM]
# Add customizations here, e.g., set GCAM.Root to another directory
"""

_ConfigParser = None

def readConfigFiles():
    global _ConfigParser

    home = os.getenv('HOME')
    platformName = platform.system()

    assert platformName in ('Darwin', 'Linux'), "Only Darwin (OS X) and Linux are supported currently"

    if platformName == 'Darwin':
        jarFile = '%(GCAM.ModelInterface)s/ModelInterface.app/Contents/Resources/Java/ModelInterface.jar'
        exeFile = 'Release/objects'
    elif platformName == 'Linux':
        jarFile = '%(GCAM.ModelInterface)s/ModelInterface.jar'
        exeFile = './gcam.exe'

    # Initialize config parser with default values
    _ConfigParser = SafeConfigParser()
    _ConfigParser.readfp(io.BytesIO(_SystemDefaults))
    _ConfigParser.set(GCAM_SECTION, 'Home', home)
    _ConfigParser.set(GCAM_SECTION, 'GCAM.Executable', exeFile)
    _ConfigParser.set(GCAM_SECTION, 'GCAM.JarFile', jarFile)


    # Customizations are stored in ~/.gcam.cfg
    usrConfigPath = os.path.join(home, USR_CONFIG_FILE)
    if os.path.exists(usrConfigPath):
        _ConfigParser.readfp(open(usrConfigPath))
    else:
        # create an empty file with the [GCAM] section if no file exists
        with open(usrConfigPath, 'w') as fp:
            fp.write("[%s]\n" % GCAM_SECTION)
            fp.write(_UserDefaults)

    return _ConfigParser


def getParam(varName):
    return _ConfigParser.get(GCAM_SECTION, varName)


def getParamAsBoolean(varName):
    value = getParam(varName)
    return value and str(value).lower() in ('true', 'yes', 'on', '1') # added str() to avoid spurious error message
